//
//  PurchaseViewController.m
//  yigou
//
//  Created by wangdianlei on 2017/1/13.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "PurchaseViewController.h"
#import "PurchaseInfoCell.h"
#import "PurchaseWordsCell.h"
#import "GGActionSheet.h"
#import "WXApi.h"
#import "MMWxPay.h"
#import "MMAddress.h"
#import "AddressListViewController.h"
#import "PurchaseAddressCell.h"

@interface PurchaseViewController () <UITableViewDelegate, UITableViewDataSource,GGActionSheetDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *price;
@property (weak, nonatomic) IBOutlet UIButton *buybtn;
@property(nonatomic,strong) GGActionSheet *actionSheetImg;
@property (strong, nonatomic) NSString *orderid;
@property (assign, nonatomic) BOOL addressSelect;
@property (strong, nonatomic) NSMutableArray *addressArray;

@end

@implementation PurchaseViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:POST_UPDATEP object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MSGSELECTADDRESS object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    UIView *blankView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 1)];
    self.tableView.tableFooterView = blankView;
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickTable:)];
//    tap.numberOfTapsRequired = 1;
//    [self.tableView addGestureRecognizer:tap];
    
    [self.buybtn.layer setBorderWidth:1];
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef colorref = CGColorCreate(colorSpace, (CGFloat[]){0.05, 0.63, 0.71, 1});
    [self.buybtn.layer setBorderColor:colorref];
    CGColorRelease(colorref);
    CGColorSpaceRelease(colorSpace);
    
    self.orderid = @"";
    self.addressSelect = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updatePrice) name:POST_UPDATEP object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateAddress) name:MSGSELECTADDRESS object:nil];
    //重置数量为1
    [DataCenter sharedDataCenter].purchaseCount = 1;
    [DataCenter sharedDataCenter].purchaseWords = @"";
    
    CGFloat iprice = [self.gooddata.market_price floatValue];
    self.price.text = [NSString stringWithFormat:@"实付：%.2f", iprice];
    
    [self requestAddressList];
}

- (void)requestAddressList {
    NSString *urlStr = [NSString stringWithFormat:@"%@/userCenter/addressList",APIYIGOU];
    
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = urlStr;
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        [JSONModel addDatasFromDict:dict withModel:@"MMAddress" forKey:@"data" target:self.addressArray isAppend:NO];
        for(NSInteger i = 0; i < self.addressArray.count; i++) {
            MMAddress *one = self.addressArray[i];
            if (one.is_default == 1) {
                self.addressSelect = YES;
                [DataCenter sharedDataCenter].purchaseAddress = [Address new];
                [DataCenter sharedDataCenter].purchaseAddress.address_id = one.address_id;
                [DataCenter sharedDataCenter].purchaseAddress.address_info = one.address_info;
                [DataCenter sharedDataCenter].purchaseAddress.name = one.name;
                [DataCenter sharedDataCenter].purchaseAddress.mobile = one.mobile;
                [self.tableView reloadData];
            }
        }
    } error:^(YTKBaseRequest *request) {
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [ViewFactory setNavigationBlack:self];
    self.navigationItem.titleView = [ViewFactory makeNavigationTitle:@"确认订单"];
    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBackWhite:self action:@selector(goPop)];
    self.navigationItem.leftBarButtonItem = backBtn;
}

- (void)clickTable:(UITapGestureRecognizer*)recognizer {
    [self.view endEditing:YES];
}


- (void)goPop {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)updatePrice {
    CGFloat iprice = [self.gooddata.market_price floatValue];
    CGFloat final = iprice * [DataCenter sharedDataCenter].purchaseCount;
    self.price.text = [NSString stringWithFormat:@"实付：%.2f", final];
}

- (void)updateAddress {
    self.addressSelect = YES;
    [self.tableView reloadData];
}

- (IBAction)clickBuy:(id)sender {
    [self getPayType];
}

- (void)setCellStyle:(UITableViewCell *)cell {
    cell.textLabel.textColor = [UIColor colorWithHexString:@"3d3d3d"];
    cell.textLabel.font = [FontTool fontWithSize:14];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        if (!self.addressSelect)
            return 50;
        else
            return 95;
    } else if (indexPath.row == 1) {
        return 175;
    } else if (indexPath.row == 2) {
        return 120;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        if (!self.addressSelect) {
            UITableViewCell *cell = GET_SYSTEM_CELL(Default, @"setdefault");
            [self setCellStyle:cell];
            cell.textLabel.text = @"请填写收货地址";
            cell.imageView.image = [UIImage imageNamed:@"posindex"];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return cell;
        } else {
            PurchaseAddressCell *cell = GET_CELL(PurchaseAddressCell, @"PurchaseAddressCell");
            if ([DataCenter sharedDataCenter].purchaseAddress) {
                cell.nameLable.text = [DataCenter sharedDataCenter].purchaseAddress.name;
                cell.phoneNumber.text = [DataCenter sharedDataCenter].purchaseAddress.mobile;
                cell.introdocLable.text = [DataCenter sharedDataCenter].purchaseAddress.address_info;
            }
            return cell;
        }
    } else if (indexPath.row == 1) {
        PurchaseInfoCell *cell = GET_CELL(PurchaseInfoCell, @"PurchaseInfoCell");
        [cell fillWithData:self.gooddata];
        return cell;
    } else if (indexPath.row == 2) {
        PurchaseWordsCell *cell = GET_CELL(PurchaseWordsCell, @"PurchaseWordsCell");
        return cell;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        AddressListViewController *vc = [[AddressListViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)getPayType {
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = [NSString stringWithFormat:@"%@/product/showPayType", APIYIGOU];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        //NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        [self.actionSheetImg showGGActionSheet];
    } error:^(YTKBaseRequest *request) {
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}

- (void)getOrderInfo {
    NSString *addressid = @"";
    if ([DataCenter sharedDataCenter].purchaseAddress) {
        addressid = [DataCenter sharedDataCenter].purchaseAddress.address_id;
    } else {
        [ViewFactory showInfoMsg:@"请选择收获地址！"];
        return;
    }
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/order/orderInfo?product_id=%lld&address_id=%ld&product_count=%ld&remark=%@", APIYIGOU, [self.productId longLongValue], [addressid integerValue], [DataCenter sharedDataCenter].purchaseCount, [DataCenter sharedDataCenter].purchaseWords];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [ViewFactory showLoading];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        self.orderid = [[dict objectForKey:@"data"] objectForKey:@"order_id"];
        [self wxToPay];
        [ViewFactory dismissLoading];
    } error:^(YTKBaseRequest *request) {
        [ViewFactory dismissLoading];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}

- (void)wxToPay {
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = [NSString stringWithFormat:@"%@/wxpay/topay?relationOrderSn=%@&user_id=%@", APIYIGOU, self.orderid, [UserData userid]];
    [ViewFactory showLoading];
    [request dyOtherStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        DYLog(@"response:%@", request.responseString);
        NSDictionary *dict = [request.responseString JSONObject];
        MMWxPay *wxpay = [[MMWxPay alloc] initWithDictionary:[dict objectForKey:@"data"]  error:nil];
        if (wxpay) {
            PayReq *payreq = [[PayReq alloc] init];
            payreq.partnerId = WXPARTNERID;
            //TODO:微信支付retcode 有误
            payreq.package = wxpay.package;
            payreq.prepayId = wxpay.prepayid;
            payreq.nonceStr = wxpay.noncestr;
            payreq.timeStamp = [wxpay.timestamp integerValue];
            payreq.sign = wxpay.sign;
            [WXApi sendReq:payreq];
        }
    } error:^(YTKBaseRequest *request) {
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}

#pragma mark - GGActionSheet代理方法
-(void)GGActionSheetClickWithIndex:(int)index{
    NSLog(@"--------->点击了第%d个按钮<----------",index);
    if ([WXApi isWXAppInstalled] && [WXApi isWXAppSupportApi]) {
        [self getOrderInfo];
    } else {
        [ViewFactory showInfoMsg:@"您还没有安装微信'，请用其他支付方式"];
    }
}

-(GGActionSheet *)actionSheetImg{
    if (!_actionSheetImg) {
        _actionSheetImg = [GGActionSheet ActionSheetWithImageArray:@[/*@"alipay233",*/@"wechatpay233"] delegate:self];
        _actionSheetImg.cancelDefaultColor = [UIColor redColor];
    }
    return _actionSheetImg;
}

ARRAY_INIT(addressArray)

@end
